import os
import json

def fix_image_path_in_json(json_dir):
    """
    遍历指定目录下的所有JSON文件，统一修改imagePath格式
    """
    if not os.path.exists(json_dir):
        print(f"目录不存在: {json_dir}")
        return
    fixed_count = 0
    total_count = 0
    # 遍历目录下的所有JSON文件
    for filename in os.listdir(json_dir):
        if filename.endswith('.json'):
            total_count += 1
            json_path = os.path.join(json_dir, filename)
            
            try:
                # 读取JSON文件
                with open(json_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                # 获取当前imagePath和图片文件名
                current_image_path = data.get('imagePath', '')
                image_filename = os.path.basename(current_image_path)
                
                # 生成正确的imagePath格式
                correct_image_path = f"..\\C1\\{image_filename}"
                
                # 如果当前格式不正确，进行修改
                if current_image_path != correct_image_path:
                    print(f"修复: {current_image_path} -> {correct_image_path}")
                    data['imagePath'] = correct_image_path
                    
                    # 写回原文件
                    with open(json_path, 'w', encoding='utf-8') as f:
                        json.dump(data, f, indent=2, ensure_ascii=False)
                    
                    fixed_count += 1
                else:
                    print(f"格式正确，跳过: {filename}")
                    
            except Exception as e:
                print(f"处理文件 {filename} 时出错: {e}")
    
    print(f"\n处理完成！共检查 {total_count} 个文件，修复了 {fixed_count} 个文件的imagePath格式。")

if __name__ == '__main__':
    # 直接指定C2_Result目录路径
    json_directory = "C1_Label"
    fix_image_path_in_json(json_directory)